package com.wt.demo;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @description
 * @author: wangtao
 * @date:16:10 2019/6/17
 * @email:386427665@qq.com
 */
public class ThreadPoolExecutorExtend {

    public static class MyTask implements Runnable {

        String name;

        public MyTask(String name) {
            this.name = name;
        }

        @Override
        public void run() {
            System.out.println("正在执行：ThreadID = " + Thread.currentThread().getId() + ": Task name = " + name);
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        ExecutorService exec = new ThreadPoolExecutor(5, 5, 0, TimeUnit.SECONDS, new ArrayBlockingQueue<>(5)) {
            @Override
            protected void beforeExecute(Thread t, Runnable r) {
                System.out.println("准备执行：ThreadID = " + Thread.currentThread().getId() + ": Task name = " + ((MyTask) r).name);
            }

            @Override
            protected void afterExecute(Runnable r, Throwable t) {
                System.out.println("执行完成：ThreadID = " + Thread.currentThread().getId() + ": Task name = " + ((MyTask) r).name);
            }

            @Override
            protected void terminated() {
                System.out.println("线程池退出");
            }
        };

        for (int i = 0; i < 5; i++) {
            exec.execute(new MyTask("MyTask-" + i));
            Thread.sleep(200);
        }
        exec.shutdown();
    }

}
